package cn.com.cfae.iras.doc.analyze.components.consistency;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by zouxun on 2018/10/29
 */
@Component("U1014")
@Scope("prototype")
public class U1014 extends BaseComponent {
    private static Logger logger = LoggerFactory.getLogger(U1014.class);

    @Autowired
    U1004 u1004;

    /**
     * @desc 检查募集说明书，提及的企业、主承销商及其他承销机构、律师事务所、会计师事务所、信用增进机构、信用评级机构、登记托管、结算机构以及其他与发行有关机构等的名称是否一致
     * @return
     */
    @Override
    public List<ComponentResult> handlerM() {
        logger.info("开始调用U1014组件，处理M表...............");
//        DocumentModel documentModel = super.getExtractData();
//        ChapterModel chapterModelM0 = documentModel.getChapterModel("M-0");
//        ChapterModel chapterModelM3 = documentModel.getChapterModel("M-3");
//        ChapterModel chapterModelM5 = documentModel.getChapterModel("M-5");
//        ChapterModel chapterModelM7 = documentModel.getChapterModel("M-7");
//        ChapterModel chapterModelM8 = documentModel.getChapterModel("M-8");
//        ChapterModel chapterModelM12 = documentModel.getChapterModel("M-12");
//        ChapterModel chapterModelM13 = documentModel.getChapterModel("M-13");
        String checkType="M";
        String model="M-12";
        List<ComponentResult> componentResults  = ruleCheck(checkType,model);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        logger.info("开始调用U1014组件，处理BM表...............");
        String checkType="BM";
        String model="BM-12";
        List<ComponentResult> componentResults  = ruleCheck(checkType,model);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        logger.info("开始调用U1014组件，处理DM表...............");
        String checkType="DM";
        String model="DM-12";
        List<ComponentResult> componentResults  = ruleCheck(checkType,model);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        logger.info("开始调用U1014组件，处理BDM表...............");
        String checkType="BDM";
        String model="BDM-12";
        List<ComponentResult> componentResults  = ruleCheck(checkType,model);
        return componentResults;
    }

    public Map<String,ExtractItem> getExtractItemMap(ChapterModel chapterModel,String catalogId,Map<String,String> itemMap){
        Map<String,ExtractItem> extractItemMap = new HashMap<>();

        Set<String> itemNameSet=itemMap.keySet();

        for(String itemName:itemNameSet){
            String[] itemNameArray=itemMap.get(itemName).split("\\|");
            logger.info("itemNameArray[0]：{},itemNameArray[1]：{}",itemNameArray[0],itemNameArray[1]);

            if(chapterModel!=null){
                KVText kvTextValue = getKVTextValue(catalogId,itemNameArray[0],itemNameArray[1]);

                if(kvTextValue!=null){
                    if(StringUtils.isNotEmpty(kvTextValue.getText())){
                        //登记托管机构
                        if(itemNameArray[1].equals("DJTGJG")){
                            if(kvTextValue.getText().contains("上海清算所")){
                                kvTextValue.setText("上海清算所");
                            }else if(kvTextValue.getText().contains("银行间市场清算所股份有限公司")){
                                kvTextValue.setText("银行间市场清算所股份有限公司");
                            }
                        }

                        ExtractItem extractItem = chapterModel.getModel(itemNameArray[0]).getExtractItem(itemNameArray[1]);
                        extractItemMap.put(itemName,extractItem);
                    }else{
                        extractItemMap.put(itemName,null);
                    }
                }else{
                    extractItemMap.put(itemName,null);
                }
            }else{
                extractItemMap.put(itemName,null);
            }
        }
        return extractItemMap;
    }

    private String dealText(String text){
        return text.replaceAll("[。|,|，|.|\\s]{1,}","");
    }

    //规则检查
    private List<ComponentResult> ruleCheck(String checkType,String model){
        DocumentModel documentModel = super.getExtractData();

        List<ComponentResult> componentResults = new ArrayList<>();

        try{
            Map<String,String> itemNameMap = new HashMap<>();
            itemNameMap.put("FXR","发行人名称");
            itemNameMap.put("XYPJJG","信用评级机构");
            itemNameMap.put("ZCXS","主承销商");
            itemNameMap.put("XYZJJG","信用增进机构");
            itemNameMap.put("DJTGJG","登记托管机构");

            //M-12与发行有关的机构
            Map<String,String> m12ItemMap = new HashMap<>();
            m12ItemMap.put("FXR","FXR|FXRMC"); //发行人名称
            m12ItemMap.put("XYPJJG","XYPJJG|MC");//信用评级机构名称
            m12ItemMap.put("ZCXS","ZCXS|MC");//主承销商
            m12ItemMap.put("XYZJJG","XYZJJG|MC");//信用增进机构名称
            m12ItemMap.put("DJTGJG","DJTG|MC");//登记托管机构名称

            //M-0扉页
            Map<String,String> m0ItemMap = new HashMap<>();
            m0ItemMap.put("FXR","FXR|FXRMC"); //发行人名称
            m0ItemMap.put("XYPJJG","FXTK|XYPJJG");//信用评级机构名称
            m0ItemMap.put("ZCXS","ZCXS|MC");//主承销商名称
            m0ItemMap.put("XYZJJG","XYZJJG|MC");//信用增进机构名称

            //M-3发行条款
            Map<String,String> m3ItemMap = new HashMap<>();
            m3ItemMap.put("FXR","FXTK|FXR");//发行人名称
            m3ItemMap.put("DJTGJG","FXTK|DJTGJG");//登记托管机构名称
            m3ItemMap.put("XYPJJG","FXTK|XYPJJG");//信用评级机构名称
            m3ItemMap.put("XYZJJG","FXTK|ZJ");//信用增进机构/担保
            m3ItemMap.put("ZCXS","FXTK|ZCXS");//主承销商

            //M-5发行人的基本信息
            Map<String,String> m5ItemMap = new HashMap<>();
            m5ItemMap.put("FXR","FXR|FXRMC");//发行人名称

            //M-7发行人资信情况
            Map<String,String> m7ItemMap = new HashMap<>();
            m7ItemMap.put("XYPJJG","XYPJJG|MC");//信用评级机构名称

            //M-8信用增进机构
            Map<String,String> m8ItemMap = new HashMap<>();
            m8ItemMap.put("XYZJJG","XYZJJG|MC");//信用增进机构名称

            //M-13备查文件
            Map<String,String> m13ItemMap = new HashMap<>();
            m13ItemMap.put("FXR","FXR|FXRMC");//发行人名称
            m13ItemMap.put("ZCXS","ZCXS|MC");//主承销商名称

            Map<String,Map<String,String>> checkModelMap=new HashMap<>();

            if(checkType.equals("M")){
                checkModelMap.put("M-0",m0ItemMap);
                checkModelMap.put("M-3",m3ItemMap);
                checkModelMap.put("M-5",m5ItemMap);
                checkModelMap.put("M-7",m7ItemMap);
                checkModelMap.put("M-8",m8ItemMap);
                checkModelMap.put("M-13",m13ItemMap);
            }else if(checkType.equals("BM")){
                checkModelMap.put("BM-0",m0ItemMap);
                checkModelMap.put("BM-3",m3ItemMap);
                checkModelMap.put("BM-5",m5ItemMap);
                checkModelMap.put("BM-7",m7ItemMap);
                checkModelMap.put("BM-8",m8ItemMap);
                checkModelMap.put("BM-13",m13ItemMap);
            }else if(checkType.equals("DM")){
                checkModelMap.put("DM-0",m0ItemMap);
                checkModelMap.put("DM-3",m3ItemMap);
                checkModelMap.put("DM-5",m5ItemMap);
                checkModelMap.put("DM-7",m7ItemMap);
                checkModelMap.put("DM-8",m8ItemMap);
                checkModelMap.put("DM-13",m13ItemMap);
            }else if(checkType.equals("BDM")){
                checkModelMap.put("BDM-0",m0ItemMap);
                checkModelMap.put("BDM-3",m3ItemMap);
                checkModelMap.put("BDM-5",m5ItemMap);
                checkModelMap.put("BDM-7",m7ItemMap);
                checkModelMap.put("BDM-8",m8ItemMap);
                checkModelMap.put("BDM-13",m13ItemMap);
            }

            List<String> textPositionByKeyList = new ArrayList<>();
            textPositionByKeyList.add("M-0");
            textPositionByKeyList.add("BM-0");
            textPositionByKeyList.add("DM-0");
            textPositionByKeyList.add("BDM-0");

            Map<String,String> m12ValueMap = new HashMap<>();

            ChapterModel m12ChapterModel = documentModel.getChapterModel(getCatalogId());

            Set<String> m12ItemSet = m12ItemMap.keySet();

            for (String m12Item : m12ItemSet) {
                logger.info("章节:{},条目:{}", getCatalogId(), m12Item);
                String m12Str = m12ItemMap.get(m12Item);
                String[] m12StrArray = m12Str.split("\\|");
                String m12ModelName = m12StrArray[0];
                String m12ItemName = m12StrArray[1];

                if (m12ChapterModel != null) {
                    KVText kvText = getKVTextValue(getCatalogId(), m12ModelName, m12ItemName);

                    if (kvText != null) {
                        String m12Text = kvText.getText();
                        if (StringUtils.isNotEmpty(m12Text)) {
                            logger.info("抽取到数值:{}", m12Text);
                            m12Text = dealText(m12Text);
                            logger.info("数据处理：{}",m12Text);
                            m12ValueMap.put(m12Item, m12Text);
                        } else {
                            logger.info("未抽取到数值");
                            m12ValueMap.put(m12Item, "05");
                        }
                    } else {
                        logger.info("未抽取到数值");
                        m12ValueMap.put(m12Item, "05");
                    }
                }else{
                    logger.info("未识别第十二章的数据");
                    m12ValueMap.put(m12Item, "05");
                }
            }

            //不一致
            int inconformityCount = 0;
            //一致
            int consistentCount = 0;
            //未识别
            int unidentification=0;

            Set<String> checkModelSet=checkModelMap.keySet();

            for(String checkModel:checkModelSet){
                logger.info("当前检查的章节：{}",checkModel);
                ChapterModel chapterModel = documentModel.getChapterModel(checkModel);

                Map<String,ExtractItem> extractItemMap=getExtractItemMap(chapterModel,checkModel,checkModelMap.get(checkModel));

                Set<String> extractItemNameSet = extractItemMap.keySet();

                for(String extractItemName:extractItemNameSet){
                    logger.info("extractItemName:{}",extractItemName);

                    String itemName = itemNameMap.get(extractItemName);

                    String keyword = checkModel.concat(itemName).concat(" 对比 ").concat(getCatalogId()).concat(itemName);

                    ComponentResult componentResult = u1004.getComponentResult(getCatalogId(),getCatalogId(),getRuleTitle(),keyword,"",true,getRegulationId(),3,null,"03");

                    if(chapterModel!=null){
                        componentResult.setPageNum(chapterModel.getStartPage());
                    }

                    ExtractItem extractItem = extractItemMap.get(extractItemName);

                    String m12Text = m12ValueMap.get(extractItemName);

                    logger.info("条目：{}，章节：M-12，值：{}",itemName,m12Text);

                    if(extractItem != null){
                        logger.info("条目：{}，章节：{}，值：{}", itemName, checkModel, extractItem.getValue().getText());

                        KVText kvTextKey = extractItem.getKey();
                        KVText kvTextValue = extractItem.getValue();

                        List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();

                        TextLayout textLayout = null;

                        if(textPositionByKeyList.contains(checkModel)){
                            if(extractItemName.equals("XYPJJG")){
                                if(kvTextKey!=null){
                                    textLayout = kvTextKey.getTextLayout();
                                }
                            }else{
                                if(kvTextValue!=null){
                                    textLayout = kvTextValue.getTextLayout();
                                }
                            }
                        }else{
                            if(kvTextKey!=null){
                                textLayout = kvTextKey.getTextLayout();
                            }
                        }

                        if(textLayout!=null){
                            ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                            textPosition.setContent(textLayout.getText());
                            textPosition.setX(textLayout.getLeft());
                            textPosition.setY(textLayout.getTop());
                            componentResult.setPageNum(textLayout.getPageNumber());
                            textPositionList.add(textPosition);
                        }

                        componentResult.setTextPosition(textPositionList);
//                        componentResult.setAnnotationFlag(false);

                        if("05".equals(m12Text)){
                            String promptMessage = "已识别".concat(checkModel).concat(itemName).concat("：").concat(kvTextValue.getText()).concat("，未识别").concat(getCatalogId()).concat(itemName).concat("，建议人工核对");
                            logger.info("promptMessage：{}", promptMessage);
                            componentResult.setPromptMessage(promptMessage);
                        }else{
                            String text = kvTextValue.getText();

                            String promptMessage = checkModel.concat(itemName).concat("：").concat(text).concat("，").concat(getCatalogId()).concat(itemName).concat("：").concat(m12Text);

                            text = dealText(text);

                            logger.info("数据处理：{}",text);

                            if(extractItemName.equals("DJTGJG")){
                                if(text.contains("上海清算所")){
                                    text = "银行间市场清算所股份有限公司";
                                }
                                if(m12Text.contains("上海清算所")){
                                    m12Text = "银行间市场清算所股份有限公司";
                                }
                            }

                            if(text.contains(m12Text)){
                                logger.info("对比一致");
                                componentResult.setPromptMessage("对比一致".concat("，").concat(promptMessage));
                                componentResult.setExist("01");
                                componentResult.setAnnotationFlag(false);
                                consistentCount++;
                            }else{
                                if(m12Text.contains(text)){
                                    logger.info("对比一致");
                                    componentResult.setPromptMessage("对比一致".concat("，").concat(promptMessage));
                                    componentResult.setExist("01");
                                    componentResult.setAnnotationFlag(false);
                                    consistentCount++;
                                }else{
                                    if(extractItemName.equals("XYPJJG")){
                                        if(m12Text.length()>5){
                                            m12Text = m12Text.substring(0,5);
                                        }

                                        if(text.contains(m12Text)){
                                            logger.info("对比一致");
                                            componentResult.setPromptMessage("对比一致".concat("，").concat(promptMessage));
                                            componentResult.setExist("01");
                                            componentResult.setAnnotationFlag(false);
                                            consistentCount++;
                                        }else{
                                            logger.info("对比不一致");
                                            componentResult.setPromptMessage("对比不一致".concat("，").concat(promptMessage));
                                            componentResult.setExist("02");
                                            inconformityCount++;
                                        }

                                    }else{
                                        logger.info("对比不一致");
                                        componentResult.setPromptMessage("对比不一致".concat("，").concat(promptMessage));
                                        componentResult.setExist("02");
                                        inconformityCount++;
                                    }
                                }
                            }

                        }
                        componentResults.add(componentResult);
                    }else{
                        String promptMessage=null;
                        if(!"05".equals(m12Text)){
                            promptMessage = "未识别".concat(checkModel).concat(itemName).concat("，已识别").concat(getCatalogId()).concat(itemName).concat("：").concat(m12Text).concat("，建议人工核对");
                        }else{
                            promptMessage = "未识别".concat(checkModel).concat(itemName).concat("，未识别").concat(getCatalogId()).concat(itemName).concat("，建议人工核对");
                        }
                        logger.info("promptMessage：{}",promptMessage);
                        componentResult.setPromptMessage(promptMessage);
                        componentResults.add(componentResult);
                        unidentification++;
                    }

                }
            }

            if(componentResults.size()>0){
                if(inconformityCount>0){
                    for(ComponentResult componentResult : componentResults) {
                        componentResult.setExist("02");
                    }
                    return componentResults;
                }else{
                    if(unidentification>0){
                        for(ComponentResult componentResult : componentResults) {
                            componentResult.setExist("03");
                        }
                        return componentResults;
                    }else{
                        if(consistentCount>0){
                            for(ComponentResult componentResult : componentResults) {
                                componentResult.setExist("01");
                                componentResult.setAnnotationFlag(false);
                            }
                            return componentResults;
                        }
                    }
                }
            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }

        return componentResults;
    }

}
